/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.security.iplocator;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Charsets;
import org.vacoor.nothing.common.json.Jacksons;
import org.vacoor.nothing.common.util.HttpUtils;
import org.vacoor.nothing.common.util.IOUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author vacoor
 */
public class BaiduIPLocator implements IPLocator {
    //http://developer.baidu.com/map/index.php?title=webapi/ip-api
    static final String API = "http://api.map.baidu.com/location/ip?ak=#AK#&ip=#IP#";
    //http://lbs.amap.com/api/javascript-api/example/g/0703-2/#
    //http://restapi.amap.com/v3/ip?key=76666ae2f5f2d75a7b368fe0a1199482&s=rsv3&callback=jsonp_628138_

    public static void main(String[] args) throws IOException {
    }

    @Override
    public String locate(String ip) {
        try {
            String url = API.replace("#AK#", "F454f8a5efe5e577997931cc01de3974").replace("#IP#", ip);
            InputStream is = HttpUtils.get(url, null, 1000);
            String s = IOUtils.readText(is, Charsets.UTF_8, true);
            JsonNode root = Jacksons.deserialize(s, JsonNode.class);
            String address = root.get("content").get("address").asText();
            return address;
        } catch (IOException e) {
            return "";
        }
    }
}
